package leetcode.wanggetu;

public class Test2 {
    public static void main(String[] args) {
        int[][] grid = {
                {1, 1, 1, 1, 0},
                {1, 1, 0, 1, 0},
                {1, 1, 0, 0, 0},
                {0, 0, 0, 0, 0}
        };
        System.out.println(numIslands(grid));
    }

    public static int numIslands(int[][] grid) {
        int num = 0;
        for (int i = 0; i < grid.length; i++) {
            int[] ints = grid[i];
            for (int i1 = 0; i1 < ints.length; i1++) {
                if (ints[i1] == 1) {
                    int a = dfs(grid, i, i1);
                    num = Math.max(a, num);
                }
            }
        }
        return num;
    }

    private static int dfs(int[][] grid, int r, int c) {
        if (!inArea(grid, r, c)) {
            return 0;
        }
        if (grid[r][c] != 1) {
            return 0;
        }
        grid[r][c] = 2;
        return 1 + dfs(grid, r - 1, c)
                + dfs(grid, r + 1, c)
                + dfs(grid, r, c - 1)
                + dfs(grid, r, c + 1);
    }

    private static boolean inArea(int[][] grid, int r, int c) {
        return r >= 0 && r < grid.length && c >= 0 && c < grid[0].length;
    }
}
